<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Send;
use app\admin\service\Rbac;
use app\common\enums\StatusEnum;
use think\facade\Request;
use app\admin\validate\Login AS LoginValidate;
use think\facade\Session;

class Login extends Base
{
    use Send;

    public function index()
    {
        if (Session::get('session_admin_id')) {
            return redirect('index/index');
        }
        if (Request::instance()->isPost()) {
            $data = input('post.');
            $userName = trim($data['user_name']);
            $password = trim($data['password']);

            // 检测变量
            $validate = new LoginValidate();
            if (!$validate->check($data)) {
                return json(self::sendResult(102, [], $validate->getError()));
            }

            $user = User::getOneByName($userName);
            if (empty($user)) {
                return json(self::sendResult(102, [], '用户不存在'));
            }

            if ($user['status'] != StatusEnum::ENABLED) {
                return json(self::sendResult(102, [], '该用户被禁用'));
            }

            $password = password($password, $user['salt']);
            if ($user['password'] != $password) {
                return json(self::sendResult(102, [], '密码错误'));
            }

            $userId = $user['id'];

            $rbac = new Rbac();
            // 找不到session数据，删除缓存
            if (!Session::get($rbac->_sessionName)) {
                // 删除登录缓存
                $rbac->delCache($userId);
            }

            // 不需要验证权限
            $noAuthAdmin = config('noAuthAdmin');
            if (in_array($userId, $noAuthAdmin)) {
                // 直接保存下cache、和session
                $rbac->setCache($userId);
                $rbac->setSession($userId);
            } else {
                // 获取权限
                $return = $rbac->cachePermission($userId);
                if ($return['code'] != self::$okCode) {
                    return json(self::sendResult($return['code'], [], $return['msg']));
                }
            }

            // 修改用户的最后登录时间
            $user->last_login_time = time();
            $user->save();

            // 保存登录信息
            Session::set('session_admin_id', $userId);
            Session::set('session_admin_info', $user->toArray());

            return json(self::sendResult(self::$okCode, [
                'url' => url('index/index'),
            ]));
        } else {
            return view('index');
        }
    }
}
